<template>
	<view class="order-container">
		<!-- 顶部选项卡 (维修人员和普通用户共用) -->
		<view class="tabs">
			<view v-for="(item, index) in tabList" :key="index" class="tab-item"
				:class="{ active: currentTab === index }" @click="switchTab(index)">
				{{ item.name }}
			</view>
		</view>

		<!-- 加载提示 -->
		<view v-if="loading && orderList.length === 0" class="loading-state">
			<uni-load-more status="loading"></uni-load-more>
		</view>

		<!-- 工单列表 -->
		<view class="order-list" v-if="orderList.length > 0">
			<view class="order-item" v-for="(item, index) in orderList" :key="item.id" @click="goToDetail(item.id)">
				<view class="order-header">
					<view class="order-no">工单号: {{ item.id }}</view>
					<!-- 状态显示，增加不同颜色 -->
					<view class="order-status" :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</view>
				</view>
				<view class="order-content">
					<view class="content-row">
						<text class="label">报修时间：</text>
						<text class="value">{{ item.createTime }}</text>
					</view>
					<view class="content-row">
						<text class="label">联系人：</text>
						<text class="value">{{ item.contactName }}</text>
					</view>
					<view class="content-row">
						<text class="label">联系电话：</text>
						<text class="value">{{ item.contactPhone }}</text>
					</view>
					<view class="content-row">
						<text class="label">故障描述：</text>
						<text class="value">{{ item.content }}</text>
					</view>
					<view class="content-row">
						<text class="label">维修地址：</text>
						<text class="value">{{ item.location }}</text>
					</view>
				</view>
				<!-- 维修人员的操作按钮 (如果需要) -->
				<view class="order-footer" v-if="isRepairer">
					<button class="btn btn-action" v-if="item.status === 0" @click.stop="acceptOrder(item.id)">接单</button>
					<button class="btn btn-action" v-if="item.status === 1" @click.stop="completeOrder(item.id)">完成维修</button>
				</view>
				<!-- 普通用户的操作按钮 -->
				<view class="order-footer" v-else>
					<!-- 已完成但未评价的工单显示评价按钮 -->
					<text class="evaluation-tag" v-if="item.status === 2 && item.evaluated">已评价</text>
					<button class="btn btn-action" v-if="item.status === 2 && !item.evaluated" @click.stop="openEvaluation(item.id)">去评价</button>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="!loading && orderList.length === 0">
			<image class="empty-image" src="/static/tabbar/order.png" mode="aspectFit"></image>
			<text class="empty-text">暂无工单记录</text>
		</view>
		
		<!-- 加载更多 -->
		<view v-if="!loading && orderList.length > 0">
			<uni-load-more :status="finished ? 'noMore' : 'more'"></uni-load-more>
		</view>
		
		<!-- 评价弹窗 -->
		<uni-popup ref="evaluationPopup" type="bottom" @change="popupChange">
			<view class="evaluation-form" v-if="showEvaluationForm">
				<view class="form-header">
					<text class="form-title">评价维修服务</text>
					<text class="close-btn" @click="closeEvaluation">×</text>
				</view>
				
				<view class="form-content">
					<view class="evaluation-tips">您的评价对我们很重要，感谢您的反馈！</view>
					
					<view class="rating-container">
						<text class="rating-title">服务评分</text>
						<view class="stars">
							<uni-icons v-for="i in 5" :key="i"
								:type="i <= evaluationForm.score ? 'star-filled' : 'star'"
								size="30"
								:color="i <= evaluationForm.score ? '#FFD700' : '#CCCCCC'"
								@click="evaluationForm.score = i"
							></uni-icons>
							<text class="score-text">{{ evaluationForm.score }}分</text>
						</view>
						<text class="rating-desc">{{ getRatingDesc(evaluationForm.score) }}</text>
					</view>
					
					<view class="comment-container">
						<text class="comment-title">评价内容</text>
						<textarea 
							class="comment-input"
							v-model="evaluationForm.content"
							placeholder="请输入您对维修服务的评价，如服务态度、专业程度、响应速度等（选填）"
							maxlength="200"
						></textarea>
						<text class="comment-count">{{ evaluationForm.content.length }}/200</text>
					</view>
				</view>
				
				<view class="form-footer">
					<button class="btn btn-cancel" @click="closeEvaluation">取消</button>
					<button class="btn btn-submit" @click="submitEvaluation">提交评价</button>
				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import { http } from '@/utils/request.js'
	import { checkIsRepairer } from '@/utils/auth.js' // 引入检查角色的函数

	export default {
		data() {
			return {
				isRepairer: false, // 当前用户是否为维修人员
				tabList: [
					{ name: '全部', status: -1 }, // -1 代表查询所有状态
					{ name: '待处理', status: 0 },
					{ name: '维修中', status: 1 },
					{ name: '已完成', status: 2 }
				],
				currentTab: 0,
				orderList: [],
				page: 1,
				limit: 10,
				loading: false,
				finished: false,
				// 评价相关
				showEvaluationForm: false,
				currentOrderId: null, // 当前评价的工单ID
				evaluationForm: {
					score: 5,
					content: ''
				}
			}
		},
		onLoad() {
			// 检查用户角色
			this.isRepairer = checkIsRepairer()
			console.log('当前用户是否为维修人员:', this.isRepairer)
			// 初始化加载数据
			this.loadOrderList(true)
				.then(() => {
					// 数据加载完成后检查评价状态
					if (!this.isRepairer) {
						this.checkEvaluationStatus()
					}
				})
		},
		onPullDownRefresh() {
			this.loadOrderList(true)
				.then(() => {
					// 刷新后也检查评价状态
					if (!this.isRepairer) {
						this.checkEvaluationStatus()
					}
				})
		},
		onReachBottom() {
			if (!this.finished && !this.loading) {
				this.page++
				this.loadOrderList(false)
			}
		},
		methods: {
			// 切换顶部选项卡
			switchTab(index) {
				if (this.currentTab === index) return
				this.currentTab = index
				this.loadOrderList(true) // 重新加载数据
			},

			// 加载工单列表数据
			loadOrderList(refresh = false) {
				if (this.loading) return Promise.resolve()
				this.loading = true

				if (refresh) {
					this.page = 1
					this.finished = false
					this.orderList = []
				}

				// 根据角色确定API路径
				// 维修人员: /api/task/getRepairTask
				// 普通用户: /api/repairNotice/getRepairInfo
				const apiUrl = this.isRepairer ? '/api/task/getRepairTask' : '/api/repairNotice/getRepairInfo'; 
				
				// 构造请求参数 (注意：普通用户接口可能不需要分页或状态参数)
				let params = {}
				if (this.isRepairer) {
					params = {
						page: this.page,
						limit: this.limit,
						status: this.tabList[this.currentTab].status
					}
				} else {
					// 普通用户接口，添加状态参数
					params = {
						status: this.tabList[this.currentTab].status
					}
				}

				return http.get(apiUrl, params)
					.then(res => {
						// 统一处理返回结构，假设成功时 code === 0
						if (res.code === 0) {
							let list = []
							
							// 普通用户接口(/api/repairNotice/getRepairInfo) 和 维修人员接口(/api/task/getRepairTask) 都可能直接返回列表
							if (Array.isArray(res.data)) {
								list = res.data
								// 因为直接返回列表，无法准确判断分页是否结束，暂时假设单次返回即结束
								this.finished = true 
							} 
							// 如果后端接口对普通用户也返回分页结构，可以在这里添加 else if 处理
							// else if (!this.isRepairer && res.data && res.data.list) { ... }
							
							const mappedData = list.map(item => ({
								...item,
								createTime: this.formatDate(item.createTime), // 格式化时间
							}))

							// 根据当前选中的tab状态进行过滤，对所有用户都适用
							const currentStatus = this.tabList[this.currentTab].status;
							if (currentStatus === -1) {
								// 全部状态
								this.orderList = mappedData;
							} else {
								// 按状态过滤
								this.orderList = mappedData.filter(item => item.status === currentStatus);
							}
							
							// 分页结束判断
							if (list.length < this.limit) { // 如果返回数据少于请求数，认为结束
								this.finished = true;
							}
						} else {
							uni.showToast({ title: res.msg || '加载失败', icon: 'none' })
							this.finished = true // 加载失败也标记为完成
						}
					})
					.catch(err => {
						console.error('获取工单列表失败：', err)
						uni.showToast({ title: '加载数据失败', icon: 'none' })
						this.finished = true // 出错也标记为完成
					})
					.finally(() => {
						this.loading = false
						uni.stopPullDownRefresh() // 停止下拉刷新动画
					})
			},

			// 获取状态文字
			getStatusText(status) {
				const statusMap = {
					0: '待处理',
					1: '维修中',
					2: '已完成'
				}
				return statusMap[status] !== undefined ? statusMap[status] : '未知状态'
			},

			// 获取状态对应的CSS类
			getStatusClass(status) {
				const classMap = {
					0: 'status-pending', // 待处理 - 橙色
					1: 'status-processing', // 维修中 - 蓝色
					2: 'status-completed' // 已完成 - 绿色
				}
				return classMap[status] || 'status-unknown'
			},

			// 跳转到工单详情页
			goToDetail(id) {
				// 跳转到详情页，传递工单ID
				uni.navigateTo({
					url: `/pages/order/detail?id=${id}`
				})
			},

			// 格式化日期
			formatDate(dateString) {
				if (!dateString) return ''
				const date = new Date(dateString)
				if (isNaN(date.getTime())) return dateString // 如果转换失败，返回原始字符串
				const year = date.getFullYear()
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				const hours = date.getHours().toString().padStart(2, '0')
				const minutes = date.getMinutes().toString().padStart(2, '0')
				return `${year}-${month}-${day} ${hours}:${minutes}`
			},
			
			// --- 维修人员操作 --- 
			async acceptOrder(id) {
				console.log('尝试接单:', id)
				uni.showLoading({ title: '正在接单...' })
				try {
					// 调用正确的接单接口
					// 注意：使用 params 传递参数，而不是通过 data，以匹配后端的 @RequestParam
					const res = await http.post(`/api/task/updateTaskStart?id=${id}`)
					if (res.code === 0) {
						uni.showToast({ title: '接单成功', icon: 'success' })
						// 刷新列表以更新状态
						this.loadOrderList(true)
					} else {
						uni.showToast({ title: res.msg || '接单失败', icon: 'none' })
					}
				} catch (error) {
					console.error('接单异常:', error)
					uni.showToast({ title: '接单操作失败', icon: 'none' })
				} finally {
					uni.hideLoading()
				}
			},
			async completeOrder(id) {
				console.log('尝试完成维修:', id)
				uni.showLoading({ title: '正在提交...' })
				try {
					// 调用正确的完成维修接口
					// 注意：使用 params 传递参数，而不是通过 data，以匹配后端的 @RequestParam
					const res = await http.post(`/api/task/updataTaskFinish?id=${id}`)
					if (res.code === 0) {
						uni.showToast({ title: '操作成功', icon: 'success' })
						// 刷新列表以更新状态
						this.loadOrderList(true)
					} else {
						uni.showToast({ title: res.msg || '操作失败', icon: 'none' })
					}
				} catch (error) {
					console.error('完成维修异常:', error)
					uni.showToast({ title: '完成操作失败', icon: 'none' })
				} finally {
					uni.hideLoading()
				}
			},
			
			// 打开评价弹窗
			openEvaluation(id) {
				this.currentOrderId = id
				this.evaluationForm = {
					score: 5,
					content: ''
				}
				this.showEvaluationForm = true
				this.$nextTick(() => {
					this.$refs.evaluationPopup.open()
				})
			},
			
			// 关闭评价弹窗
			closeEvaluation() {
				this.showEvaluationForm = false
				this.$refs.evaluationPopup.close()
			},
			
			// 弹窗状态变化
			popupChange(e) {
				if (!e.show) {
					this.showEvaluationForm = false
				}
			},
			
			// 提交评价
			async submitEvaluation() {
				if (!this.currentOrderId) {
					uni.showToast({
						title: '工单ID无效',
						icon: 'none'
					})
					return
				}
				
				if (this.evaluationForm.score < 1 || this.evaluationForm.score > 5) {
					uni.showToast({
						title: '请选择1-5星评分',
						icon: 'none'
					})
					return
				}
				
				uni.showLoading({ title: '提交中...' })
				try {
					const data = {
						repairId: this.currentOrderId,
						score: this.evaluationForm.score,
						content: this.evaluationForm.content
					}
					
					const res = await http.post('/api/evaluation/add', data)
					
					if (res.code === 0) {
						uni.showToast({
							title: '评价成功',
							icon: 'success'
						})
						
						// 更新工单评价状态
						const order = this.orderList.find(item => item.id === this.currentOrderId)
						if (order) {
							order.evaluated = true
						}
						
						// 检查是否有打开的工单详情页，通知它刷新评价信息
						const pages = getCurrentPages()
						for (const page of pages) {
							// 如果有打开的工单详情页且是当前评价的工单
							if (page.route && page.route.includes('order/detail') && page.id === this.currentOrderId) {
								// 调用详情页的加载评价方法
								page.loadEvaluation()
							}
						}
						
						// 关闭弹窗
						this.closeEvaluation()
					} else {
						uni.showToast({
							title: res.msg || '评价失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('提交评价失败:', error)
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},
			
			// 检查工单评价状态
			async checkEvaluationStatus() {
				// 仅针对已完成的工单检查评价状态
				if (!this.isRepairer && this.orderList.length > 0) {
					const completedOrders = this.orderList.filter(item => item.status === 2)
					if (completedOrders.length === 0) return
					
					// 批量检查评价状态
					for (const order of completedOrders) {
						try {
							const res = await http.get('/api/evaluation/isEvaluated', { repairId: order.id })
							if (res.code === 0) {
								// 更新评价状态
								order.evaluated = res.data === true
							}
						} catch (error) {
							console.error('检查评价状态失败:', error)
						}
					}
				}
			},
			
			// 获取评分描述
			getRatingDesc(score) {
				const descMap = {
					1: '非常不满意',
					2: '不满意',
					3: '一般',
					4: '满意',
					5: '非常满意'
				}
				return descMap[score] || ''
			},
			
			// 对接goToEvaluation方法
			goToEvaluation(id) {
				this.openEvaluation(id)
			}
		}
	}
</script>

<style>
	.order-container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.tabs {
		display: flex;
		background-color: #fff;
		position: sticky;
		top: 0; /* 使tabs固定在顶部 */
		z-index: 100;
		border-bottom: 1rpx solid #eee;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		color: #666;
		padding: 20rpx 0;
		position: relative;
	}

	.tab-item.active {
		color: #2B65FE;
		font-weight: bold;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60rpx;
		height: 6rpx;
		background-color: #2B65FE;
		border-radius: 3rpx;
	}

	.loading-state,
	.empty-state {
		padding: 100rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	
	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}

	.empty-text {
		color: #999;
		font-size: 28rpx;
	}

	.order-list {
		padding: 20rpx;
	}

	.order-item {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		padding: 24rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
		padding-bottom: 16rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.order-no {
		font-size: 24rpx;
		color: #999;
	}

	.order-status {
		font-size: 26rpx;
		font-weight: bold;
		padding: 4rpx 12rpx;
		border-radius: 6rpx;
	}
	/* 不同状态的颜色 */
	.status-pending {
		color: #faad14; /* 橙色 */
		background-color: #fffbe6;
		border: 1rpx solid #ffe58f;
	}
	.status-processing {
		color: #1890ff; /* 蓝色 */
		background-color: #e6f7ff;
		border: 1rpx solid #91d5ff;
	}
	.status-completed {
		color: #52c41a; /* 绿色 */
		background-color: #f6ffed;
		border: 1rpx solid #b7eb8f;
	}
	.status-unknown {
		color: #bfbfbf; /* 灰色 */
		background-color: #fafafa;
		border: 1rpx solid #d9d9d9;
	}

	.order-content {
		margin-bottom: 16rpx;
	}

	.content-row {
		display: flex;
		margin-bottom: 10rpx;
		font-size: 28rpx;
	}

	.label {
		color: #666;
		width: 150rpx; /* 固定标签宽度 */
		flex-shrink: 0;
	}

	.value {
		color: #333;
		flex-grow: 1;
	}
	
	.order-footer {
		display: flex;
		justify-content: flex-end;
		padding-top: 16rpx;
		border-top: 1rpx solid #f0f0f0;
		margin-top: 16rpx;
	}
	
	.btn {
		margin-left: 16rpx;
		padding: 8rpx 24rpx;
		font-size: 26rpx;
		border-radius: 8rpx;
		line-height: 1.5;
	}
	
	.btn-action {
		background-color: #2B65FE;
		color: #fff;
	}

	/* 评价表单样式 */
	.evaluation-form {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		padding: 30rpx;
	}
	
	.form-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}
	
	.form-title {
		font-size: 32rpx;
		font-weight: bold;
	}
	
	.close-btn {
		font-size: 40rpx;
		color: #999;
		padding: 10rpx;
	}
	
	.form-content {
		margin-bottom: 30rpx;
	}
	
	.evaluation-tips {
		font-size: 26rpx;
		color: #666;
		background-color: #f8f8f8;
		padding: 20rpx;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
		text-align: center;
	}
	
	.rating-container, .comment-container {
		margin-bottom: 30rpx;
	}
	
	.rating-title, .comment-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
	}
	
	.stars {
		display: flex;
		align-items: center;
	}
	
	.score-text {
		margin-left: 20rpx;
		color: #faad14;
		font-size: 28rpx;
	}
	
	.rating-desc {
		font-size: 24rpx;
		color: #666;
		margin-top: 10rpx;
		text-align: center;
	}
	
	.comment-input {
		width: 100%;
		height: 200rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		padding: 20rpx;
		box-sizing: border-box;
		font-size: 28rpx;
	}
	
	.comment-count {
		text-align: right;
		font-size: 24rpx;
		color: #999;
		margin-top: 8rpx;
	}
	
	.form-footer {
		display: flex;
		justify-content: space-between;
	}
	
	.btn-cancel {
		background-color: #f5f5f5;
		color: #666;
		flex: 1;
		margin-right: 20rpx;
	}
	
	.btn-submit {
		background-color: #2B65FE;
		color: #fff;
		flex: 1;
		margin-left: 20rpx;
	}
	
	.evaluation-tag {
		font-size: 26rpx;
		color: #999;
		padding: 10rpx 20rpx;
	}

</style>